<template>
  <!-- 工艺参数监控规则明细表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      align-center
      class="maxhDialog1"
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
        <!-- <h4 class="mb-[20px] mt-[0px]">基本信息</h4> -->
        <el-descriptions class="margin-top mb-[20px]" :column="4" border>
          <el-descriptions-item label="工段">
            <div style="width: 100%; word-break: break-all">
              {{ formData.workshopSectionCode }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="工序">
            <div style="width: 100%; word-break: break-all">
              {{ formData.processCode }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="生产线">
            <div style="width: 100%; word-break: break-all">
              {{ formData.processEquipCode }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="设备">
            <div style="width: 100%; word-break: break-all">
              {{ formData.equipName }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="零件名称">
            <div style="width: 100%; word-break: break-all">
              {{ formData.partName }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="客户">
            <div style="width: 100%; word-break: break-all">
              {{ formData.projectName }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="型号描述">
            <div style="width: 100%; word-break: break-all">
              {{ formData.productModelName }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="产品型号">
            <div style="width: 100%; word-break: break-all">
              {{ formData.productModel }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="程序名">
            <div style="width: 100%; word-break: break-all">
              {{ formData.programName }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <h4 class="mb-[10px] mt-[0px] text-[15px] c-[#333]">参数信息</h4>
        <el-row>
          <el-col :span="8">
            <el-form-item label="参数名称" prop="parameterDesc">
              <span>{{ formData.parameterDesc }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数类型" prop="processDataType">
              <el-tag v-if="formData.processDataType === '2'">加工参数</el-tag>
              <el-tag type="success" v-if="formData.processDataType === '3'"
                >过程参数</el-tag
              >
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="监控数据类型" prop="monitorDataType">
              <el-tag v-if="formData.monitorDataType == 1">动态量</el-tag>
              <el-tag type="success" v-if="formData.monitorDataType == 2"
              >常量</el-tag
              >
              <el-tag type="warning" v-if="formData.monitorDataType == 3"
              >补偿量</el-tag
              >
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采样频度" prop="samplingFrequency">
              <div class="">
                <span>
                  {{
                    useDictionary(
                      "ScaCollectFrequency",
                      formData.samplingFrequency ?? ""
                    )
                  }}
                </span>
                <span
                  v-if="
                    formData.collectionFrequencyTime &&
                    formData.samplingFrequency == '2'
                  "
                  >&nbsp; {{ formData.collectionFrequencyTime
                  }}{{
                    formData.collectionFrequencyUnit === "s"
                      ? "秒"
                      : formData.collectionFrequencyUnit === "m"
                      ? "分钟"
                      : ""
                  }}
                </span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="第一负责人" prop="responsiblePersonName">
              <span>{{ formData.responsiblePersonName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生成工单" prop="isGenerateWorkOrder">
              <el-switch
                v-if="!props.isReadonly"
                v-model="formData.isGenerateWorkOrder"
                :active-value="1"
                :inactive-value="0"
                :disabled="props.isReadonly"
              />
              <el-switch
                v-else
                v-model="formData.isGenerateWorkOrder"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发送邮件" prop="isSendMail">
              <el-switch
                v-if="!props.isReadonly"
                v-model="formData.isSendMail"
                :active-value="1"
                :inactive-value="0"
                :disabled="props.isReadonly"
              />
              <el-switch
                v-else
                v-model="formData.isSendMail"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参考值" prop="parameterValue">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.parameterValue"
                placeholder="请输入参考值"
                clearable
              />

              <span v-else>{{ formData.parameterValue }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="控制下限" prop="lowerLimitValue">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.lowerLimitValue"
                placeholder="请输入控制下限"
                clearable
              />

              <span v-else>{{ formData.lowerLimitValue }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="控制上限" prop="upperLimitValue">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.upperLimitValue"
                placeholder="请输入控制上限"
                clearable
              />

              <span v-else>{{ formData.upperLimitValue }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <psmPatamItemContrast-diff
      v-model:visible="diffDialog.visible"
      :diffText="diffDialog.diffText"
      :title="diffDialog.title"
      :isReadonly="diffDialog.isReadonly"
      @change-visible="changeDiffVisible"
      @handle-submit="diffSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PSMPARAMITEMCONTRASTEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  parameterDesc: [],
  processDataType: [],
  parameterValue: [
    { required: true, message: "请输入参考值", trigger: "blur" },
  ],
  lowerLimitValue: [
    { required: true, message: "请输入控制下限", trigger: "blur" },
  ],
  upperLimitValue: [
    { required: true, message: "请输入控制上限", trigger: "blur" },
  ],
  samplingFrequency: [],
  isGenerateWorkOrder: [],
  isSendMail: [],
  responsiblePersonName: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  ruleId: "",
  parameterId: "",
  parameterName: "",
  parameterDesc: "",
  workshopSectionCode: "",
  processCode: "",
  equipName: "",
  partName: "",
  projectName: "",
  productModel: "",
  productModelName: "",
  processEquipCode: "",
  programName: "",
  processDataType: "",
  monitorDataType: "",
  parameterValue: "",
  lowerLimitValue: "",
  upperLimitValue: "",
  samplingFrequency: "",
  collectionFrequencyTime: "",
  collectionFrequencyUnit: "",
  isGenerateWorkOrder: "",
  isSendMail: "",
  responsiblePersonId: "",
  responsiblePersonName: "",
  enabled: "",
  deleted: "",
  remarks: "",
  changeReason: "",
  changeReasonTime: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

const detailCache = ref();
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        ruleId,
        parameterId,
        parameterName,
        parameterDesc,
        workshopSectionCode,
        processCode,
        equipName,
        partName,
        projectName,
        productModel,
        productModelName,
        processEquipCode,
        programName,
        processDataType,
        monitorDataType,
        parameterValue,
        lowerLimitValue,
        upperLimitValue,
        samplingFrequency,
        collectionFrequencyTime,
        collectionFrequencyUnit,
        isGenerateWorkOrder,
        isSendMail,
        responsiblePersonId,
        responsiblePersonName,
        enabled,
        deleted,
        remarks,
        changeReason,
        changeReasonTime,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        ruleId,
        parameterId,
        parameterName,
        parameterDesc,
        workshopSectionCode,
        processCode,
        equipName,
        partName,
        projectName,
        productModel,
        productModelName,
        processEquipCode,
        programName,
        processDataType,
        monitorDataType,
        parameterValue,
        lowerLimitValue,
        upperLimitValue,
        samplingFrequency,
        collectionFrequencyTime,
        collectionFrequencyUnit,
        isGenerateWorkOrder,
        isSendMail,
        responsiblePersonId,
        responsiblePersonName,
        enabled,
        deleted,
        remarks,
        changeReason,
        changeReasonTime,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
      detailCache.value = JSON.parse(JSON.stringify(newVal));
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.ruleId = "";
  formData.parameterId = "";
  formData.parameterName = "";
  formData.parameterDesc = "";
  formData.workshopSectionCode = "";
  formData.processCode = "";
  formData.equipName = "";
  formData.partName = "";
  formData.projectName = "";
  formData.productModel = "";
  formData.productModelName = "";
  formData.processEquipCode = "";
  formData.processDataType = "";
  formData.monitorDataType = "";
  formData.parameterValue = "";
  formData.lowerLimitValue = "";
  formData.upperLimitValue = "";
  formData.samplingFrequency = "";
  formData.collectionFrequencyTime = "";
  formData.collectionFrequencyUnit = "";
  formData.isGenerateWorkOrder = "";
  formData.isSendMail = "";
  formData.responsiblePersonId = "";
  formData.responsiblePersonName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.remarks = "";
  formData.changeReason = "";
  formData.changeReasonTime = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

const comparisonFields = [
  {
    field: "parameterValue",
    name: "参考值",
    type: "input",
  },
  {
    field: "lowerLimitValue",
    name: "控制范围下限",
    type: "input",
  },
  {
    field: "upperLimitValue",
    name: "控制范围上限",
    type: "input",
  },
  {
    field: "isGenerateWorkOrder",
    name: "生成工单",
    type: "switch",
  },
  {
    field: "isSendMail",
    name: "发送邮件",
    type: "switch",
  },
];
const compareObject = (beforeItem, afterItem) => {
  const cueText = ref("");
  // 对比每个属性
  for (const item of comparisonFields) {
    let beforeValue =
      item.type === "switch"
        ? !!beforeItem[item.field]
          ? "是"
          : "否"
        : beforeItem[item.field] ?? "空值";
    let afterValue =
      item.type === "switch"
        ? !!afterItem[item.field]
          ? "是"
          : "否"
        : afterItem[item.field] ?? "空值";
    // 如果是采样频度 则需要特殊处理
    if (item.type === "switch") {
      console.log(
        item.name,
        beforeItem[item.field],
        afterItem[item.field],
        !!beforeItem[item.field],
        !!afterItem[item.field],
        !!beforeItem[item.field] != !!afterItem[item.field]
      );
      if (!!beforeItem[item.field] != !!afterItem[item.field]) {
        if (!cueText.value) {
          cueText.value = `${beforeItem.parameterDesc}`;
        }
        cueText.value =
          cueText.value + ` ${item.name}由${beforeValue}改为${afterValue}`;
      }
    } else {
      if (beforeItem[item.field] != afterItem[item.field]) {
        if (!cueText.value) {
          cueText.value = `${beforeItem.parameterDesc}`;
        }
        cueText.value =
          cueText.value + ` ${item.name}由${beforeValue}改为${afterValue}`;
      }
    }
  }
  if (cueText.value) {
    cueText.value = cueText.value + `  请确认此变更是否合理，并填写变更记录。`;
  }
  return cueText;
};

const diffDialog = reactive({
  visible: false,
  title: "",
  diffText: "",
  isReadonly: false,
});
/** 工艺参数监控规则明细保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;

      const diff = compareObject(detailCache.value, formData);
      if (diff.value) {
        diffDialog.visible = true;
        diffDialog.diffText = diff.value;
        diffDialog.title = "修改对比";
        diffDialog.isReadonly = false;
        loading.value = false;
        return;
      }

      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/dmpDosPcm/psmparammonitordetail/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      emit("reset-table", formData.id);
      closeDialog();
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
const changeDiffVisible = (val: any) => {
  diffDialog.visible = val;
  if (val) {
    diffDialog.diffText = "";
  }
};
const diffSubmit = async (diffFormData: any) => {
  formData.changeReason = diffFormData.remarks;
  formData.changeReasonTime = diffFormData.createTime;
  await request({
    url: "/dmpDosPcm/psmparammonitordetail/updateAndSaveHis",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`编辑成功`);
  emit("reset-table", formData.id);
  closeDialog();
};
</script>
<style lang="scss" scoped>
:deep(.maxhDialog1 .el-dialog__body) {
  overflow-y: auto;
  padding: 20px;
}
</style>
